//
//  YWReleaseDemandViewController.m
//  百布业务
//
//  Created by 陈炳桦 on 15/10/27.
//  Copyright © 2015年 陈炳桦. All rights reserved.
//  发布需求

#import "YWReleaseDemandViewController.h"
#import "MLSelectPhotoAssets.h"
#import "MLSelectPhotoPickerAssetsViewController.h"
#import "MLSelectPhotoBrowserViewController.h"
#import "MLCameraViewController.h"
#import "MLPhoto.h"
#import "MBProgressHUD.h"
#import "YWSelectViewController.h"
#import "YWImageService.h"
#import "YWInputView.h"

@interface YWReleaseDemandViewController () <UITextFieldDelegate>

@property (nonatomic,strong) NSMutableArray *contentArray;

@property (nonatomic,strong) UIView *headerView;

// image数组
@property (nonatomic,strong) NSMutableArray *assets;

// 提示符
@property (nonatomic,strong) MBProgressHUD *HUD;

// 需求类型
@property (nonatomic,strong) NSString *demandFrom;

// 保存输入的文本
@property (nonatomic,strong) NSMutableDictionary *contentDic;

@end

@implementation YWReleaseDemandViewController

- (instancetype)init
{
    return [super initWithStyle:UITableViewStyleGrouped];
}

#pragma mark - 懒加载
- (NSString *)demandFrom{
    if (_demandFrom == nil) {
        _demandFrom = @"需求";
    }
    return _demandFrom;
}

- (NSMutableArray *)contentArray{
    
    if ([self.demandFrom isEqualToString:@"需求"]) {
        
        _contentArray = [NSMutableArray arrayWithArray:@[@"需求描述",@"采购手机",@"需求类型",@"其他说明",@"织法",@"克重",@"成分",@"颜色",@"手感",@"用途",@"有无样布寄回公司",@"是否能接受类似花型",@"是否能接受定做"]];
        
    }else if([self.demandFrom isEqualToString:@"下单"]){
        
        _contentArray = [NSMutableArray arrayWithArray:@[@"需求描述",@"采购手机",@"需求类型",@"其他说明",@"货号",@"颜色",@"空差",@"数量",@"价格",@"物流",@"档口名称",@"档口电话",@"档口地址",@"付款方式",@"服装公司名称",@"服装公司联系人",@"服装公司联系人电话",@"服装公司联系人地址"]];
        
    }else if([self.demandFrom isEqualToString:@"集中采购"]){
        _contentArray = [NSMutableArray arrayWithArray:@[@"需求描述",@"采购手机",@"需求类型",@"其他说明",@"货号",@"颜色",@"空差",@"数量",@"价格",@"档口名称",@"档口电话",@"档口地址",@"服装公司名称",@"服装公司联系人",@"服装公司联系人电话",@"服装公司联系人地址"]];
    }
    
    return _contentArray;
}

- (NSMutableArray *)assets{
    if (_assets == nil) {
        _assets = [NSMutableArray array];
        [_assets addObject:[UIImage imageNamed:@"take_photo_icon"]];
    }
    
    return _assets;
}

- (MBProgressHUD *)HUD{
    if (_HUD == nil) {
        _HUD = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        _HUD.mode = MBProgressHUDModeText;
        _HUD.margin = 20.f;
        [self.view addSubview:_HUD];
    }
    return _HUD;
}


- (NSMutableDictionary *)contentDic{
    if (_contentDic == nil) {
        _contentDic = [NSMutableDictionary dictionary];
    }
    return _contentDic;
}

#pragma mark - lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 加载HUD 解决莫名的Bug
    [self HUD];
    
    self.navigationItem.title = @"发布需求";
    self.view.backgroundColor =  BBRGBColor(234, 236, 238);
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self action:@selector(summit)];
    
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:@"YWSelectViewController" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endEditind) name:@"YWInputView" object:nil];
}

// 修改发布类型的通知
- (void)notification:(NSNotification *)notification{
    
    NSArray *strs = [(NSString *)notification.object componentsSeparatedByString:@"/"];
    if ([strs[1] isEqualToString:@"0"]) {
        self.demandFrom = strs[0];
        [self.tableView reloadData];
        
    }else if ([strs[1] isEqualToString:@"1"]) {
        ((UILabel *)[self.view viewWithTag:11]).text = strs[0];
    }else if ([strs[1] isEqualToString:@"2"]) {
        ((UILabel *)[self.view viewWithTag:12]).text = strs[0];
    }else if ([strs[1] isEqualToString:@"3"]) {
        ((UILabel *)[self.view viewWithTag:13]).text = strs[0];
    }
    
    
}

- (void)endEditind{
    [self.view endEditing:YES];
}

- (void)summit{

    
    NSMutableString *msg = [NSMutableString string];
    [msg appendFormat:@"需求类型: %@\n",self.demandFrom];
    [msg appendFormat:@"----------------\n"];
    [msg appendFormat:@"图片张数: %zd张\n",self.assets.count - 1];
    
    for (int i = 0; i < self.contentArray.count; i++) {
        UITextField *textField = (UITextField *)[self.view viewWithTag:i + 1];

        // 这个Bug解决方法好诡异
        if (textField.text != nil) {
            [msg appendFormat:@"%@: %@\n",self.contentArray[i],textField.text];
        }else if(self.contentDic[@(i+1)] != nil){
            [msg appendFormat:@"%@: %@\n",self.contentArray[i],self.contentDic[@(i+1)]];
        }else{
            [msg appendFormat:@"%@: %@\n",self.contentArray[i],@""];
        }
        
        
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认信息" message:msg preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self.HUD.labelText = @"提交中...";
        [self.HUD show:YES];

        
        NSString *xuqiumiaoshu = self.contentDic[@(1)];// 需求描述
        NSString *caigoushouji = self.contentDic[@(2)];;// 采购手机
        
        // 上传图片操作
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"memo"] = msg;
        param[@"mobile"] = caigoushouji;
        param[@"desc"] = xuqiumiaoshu;
        param[@"demandFrom"] = [self getDemandFrom];
        param[@"workerId"] = [YWUserInfo sharedUseInfo].workId;
        param[@"adminId"] = [YWUserInfo sharedUseInfo].workId;
        param[@"accessToken"] = [YWUserInfo sharedUseInfo].accessToken;
    
        NSLog(@"%@",param);
        NSString *url = [NSString stringWithFormat:@"%@demand/add",[YWNetwork getDomain]];
        [manager POST:url parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            
            // 拼接图片
            for (int i = 1; i < self.assets.count; i++) {
                NSData *imageData = [YWImageService compressTheBBImage:self.assets[i]];
                
                NSString *fileName = [NSString stringWithFormat:@"image.png%d",i];
                
                [formData appendPartWithFileData:imageData name:@"files" fileName:fileName mimeType:@"image/png"];
            }
            
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSLog(@"%@",responseObject);
            
            self.HUD.labelText = responseObject[@"msg"];
            [self.HUD show:YES];
            [self.HUD hide:YES afterDelay:2];
            
            NSNumber *flag = (NSNumber *)responseObject[@"flag"];
            if([flag intValue] == 1){  // 登录成功
                

                self.HUD.labelText = @"发布成功";
                [self.HUD show:YES];
                [self.HUD hide:YES afterDelay:2];
                // 两秒后返回上一级
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
           
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            self.HUD.labelText = @"出现未知错误";
            [self.HUD show:YES];
            [self.HUD hide:YES afterDelay:2];
        }];
        
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];

}


- (NSNumber *)getDemandFrom{

    if ([self.demandFrom isEqualToString:@"需求"]) {
        return @7;
    }else if ([self.demandFrom isEqualToString:@"下单"]) {
        return @8;
    }else {
        return @9;
    }
}

#pragma mark - UITableViewDataSource
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BBScreenW, 100)];
        self.headerView = headerView;
        
        [self headerViewReloadData];
        return headerView;
    }
    
    return nil;
    
}

// 重新加载headerView
- (void)headerViewReloadData{
    
    // 清空视图，防止视图重叠
    for (UIView *view in self.headerView.subviews) {
        [view removeFromSuperview];
    }
    
    CGFloat imageW = 70;
    CGFloat imageH = 70;
    CGFloat imageY = 15;
    CGFloat space = 15;     // 间距
    
    for (NSInteger i = 0; i < self.assets.count; i++) {
        CGFloat imageX = i * (imageW + space) + space;
        UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(imageX, imageY, imageW, imageH)];
        addButton.tag = i;
        
        [addButton setBackgroundImage:self.assets[i] forState:UIControlStateNormal];
        
        // 添加监听事件
        if (i == 0){
            [addButton addTarget:self action:@selector(addImage) forControlEvents:UIControlEventTouchUpInside];
        }else{
            [addButton addTarget:self action:@selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
        }
    
        [self.headerView addSubview:addButton];
    }

}

- (void)addImage{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"上传照片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    // 相机拍照
    [alert addAction:[UIAlertAction actionWithTitle:@"相机拍摄照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        __weak typeof(self)weakSelf = self;
        MLCameraViewController *cameraVc = [MLCameraViewController cameraViewController];
        cameraVc.completeBlock = ^(NSArray *photos){
            
            for (MLPhoto *camera in photos) {
                [weakSelf.assets addObject:camera.thumbImage];
            }
            [weakSelf headerViewReloadData];
        };
        [self presentViewController:cameraVc animated:YES completion:nil];
        
    }]];
    
    // 相册选择
    [alert addAction:[UIAlertAction actionWithTitle:@"相册选择照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        // 创建控制器
        MLSelectPhotoPickerViewController *pickerVc = [[MLSelectPhotoPickerViewController alloc] init];
        // 默认显示相册里面的内容SavePhotos
        pickerVc.status = PickerViewShowStatusCameraRoll;
        [pickerVc showPickerVc:self];
        __weak typeof(self) weakSelf = self;
        // 回调方法
        pickerVc.callBack = ^(NSArray *assets){
            for (MLSelectPhotoAssets *asset in assets) {
                [weakSelf.assets addObject:[MLSelectPhotoPickerViewController getImageWithImageObj:asset]];
            }
            [weakSelf headerViewReloadData];
        };
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)deleteImage:(UIButton *)button{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定要删除该图片吗？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self.assets removeObjectAtIndex:button.tag];
        [self headerViewReloadData];
        
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];

}

#pragma mark - UITextFieldDelegate
// 输入完成后保存到字典中
- (void)textFieldDidEndEditing:(UITextField *)textField{
    // 保存数据
    [self.contentDic setObject:textField.text forKey:@(textField.tag)];
}

#pragma mark - UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 100;
    }
    return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return @"以下内容仅后台可见";
    }
    
    return nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 2;
    }
    return self.contentArray.count - 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *ID = @"ID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    
    // 取消选中状态
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    
    NSInteger index = indexPath.section * 2 + indexPath.row;
    cell.textLabel.text = self.contentArray[index];
    
//    cell.accessoryView = [self getAccessoryView:indexPath];
    
    // UITextField类型
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 120, 31)];
    textField.placeholder = @"默认";
    textField.textAlignment = NSTextAlignmentRight;
    textField.inputAccessoryView = [[NSBundle mainBundle] loadNibNamed:@"YWInputView" owner:nil options:nil][0];
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.tag = index + 1;
    textField.delegate = self;
    textField.text = [self.contentDic objectForKey:@(textField.tag)];
    textField.placeholder = [NSString stringWithFormat:@"请填写%@",self.contentArray[index]];
    cell.accessoryView = textField;
    
    // 3.AccessoryView是UILabel类
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 31)];
    label.textAlignment = NSTextAlignmentRight;
    label.tag = index + 1;
    if (index == 2) {
        label.text = self.demandFrom;
        cell.accessoryView = label;
    }

    // 需求类型是需求
    if ([self.demandFrom isEqualToString:@"需求"]){
        if(index == 10){
            label.text = @"有";
            cell.accessoryView = label;
        }else if(index == 11){
            label.text = @"能";
            cell.accessoryView = label;
        }else if(index == 12){
            label.text = @"能";
            cell.accessoryView = label;
        }
        
    }
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    YWSelectViewController *selectVC = [[YWSelectViewController alloc] init];
    
    NSInteger index = indexPath.section * 2 + indexPath.row;
    if (index == 2) { // 需求类型
        
        [self.view endEditing:YES];
        selectVC.type = 0;
        [self.navigationController pushViewController:selectVC animated:YES];
        return;
    }
    
    if ([self.demandFrom isEqualToString:@"需求"]) {
        if(index == 10){  // 有无样布寄回公司
            selectVC.type = 1;
            [self.navigationController pushViewController:selectVC animated:YES];
            
        }else if(index == 11){  // 是否能接受类似花型
            selectVC.type = 2;
            [self.navigationController pushViewController:selectVC animated:YES];
            
        }else if(index == 12){  // 是否能接受定做
            selectVC.type = 3;
            [self.navigationController pushViewController:selectVC animated:YES];
            
        }
    }
    

    
}

- (void)dealloc{
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end


